//
//  LLGComposeViewController.swift
//  Weibo30LLG
//
//  Created by 李龙 on 16/8/17.
//  Copyright © 2016年 lilong. All rights reserved.
//

import UIKit
import SVProgressHUD

//发微博控制器
class LLGComposeViewController: UIViewController {

    //右侧按钮
    private lazy var rightButton: UIButton = {
    
        let button = UIButton()
        
        //添加点击事件
        button.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
        
        button.setTitle("发送", forState: .Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        
        //设置不同状态下的文字颜色
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        
        //设置不同状态下的背景图片
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        
        button.size = CGSize(width: 45, height: 30)
        return button
        
    }()
    
    //标题视图
    private lazy var titleView: UILabel = {
    
        let label = UILabel(fontSize: 17, color: UIColor.darkGrayColor())
        
        if let name = LLGUserAccountViewModel.sharedUserAccount.userAccount?.name {
        
            let result = "发微博\n\(name)"
            
            //获取name的range
            let range = (result as NSString).rangeOfString(name)
            
            let attributedStr = NSMutableAttributedString(string: result)
            
            //添加富文本属性
            attributedStr.addAttributes([
                NSForegroundColorAttributeName: UIColor.lightGrayColor(),
                NSFontAttributeName: UIFont.systemFontOfSize(14)
                ], range: range)
            
            
            label.attributedText = attributedStr
            
        } else {
        
            label.text = "发微博"
        }
        
        label.numberOfLines = 0
        label.textAlignment = .Center
        label.sizeToFit()
        
        return label
        
    }()
    
    //文本视图
    private lazy var textView: LLGComposeTextView = {
    
        let view = LLGComposeTextView()
        //设置代理
        view.delegate = self
        
        view.placeHolder = "请输入微博内容~"
        view.font = UIFont.systemFontOfSize(16)
        
        //开启垂直方向拖动
        view.alwaysBounceVertical = true
        //不想要纠错工具条
        view.autocorrectionType = .No
        
        return view
    }()
    
    //toolBar
    private lazy var toolBar: LLGComposeToolBar = {
    
        let toolBar = LLGComposeToolBar(frame: CGRectZero)
        
        return toolBar
    }()
    
    //配图
    private lazy var pictureView: LLGComposePictureView = {
    
        let view = LLGComposePictureView()
        view.backgroundColor = self.textView.backgroundColor
        return view
    }()
    
    //表情键盘
    private lazy var emoticonKyboard: LLGEmoticonKeyboard = {
    
        let keyboard = LLGEmoticonKeyboard()
        keyboard.size = CGSize(width: self.textView.width, height: 216)
        return keyboard
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }

    // MARK: --添加控件,设置约束
    private func setupUI() {
        
        view.backgroundColor = UIColor.whiteColor()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardFrameChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        setupNav()
        
        //添加控件
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        
        //设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.leading.trailing.equalTo(view)
            make.bottom.equalTo(toolBar.snp_top)
        }
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.leading.trailing.equalTo(view)
            make.height.equalTo(35)
        }
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView.snp_width).offset(-10)
            make.height.equalTo(textView.snp_width).offset(-10)
        }
        
        //toolBar闭包回调
        toolBar.didSelectedToolBarButtonClosure = { [weak self] (type: LLGComposeToolBarButtonType) in
        
            switch type {
            
            case .Picture:
                print("picture")
                self?.didSelectedPicture()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                print("表情")
                self?.didSelectedEmoticon()
            case .Add:
                print("加号")
                
            }
            
        }
        //加号按钮闭包
        pictureView.didSelectedAddImageClosure = { [weak self] in
        
            self?.didSelectedPicture()
        }
        
    }

    // MARK: --设置导航栏
    private func setupNav() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = titleView
        
    }
    
    // MARK: --leftBarButtonItem按钮点击事件
    @objc private func cancelAction() {
        
        //取消第一响应者
        self.view.endEditing(true)
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: --键盘改变的监听方法
    @objc private func keyboardFrameChange(noti: NSNotification) {
        
        //获取键盘frame
        let keyboardFrame = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        //获取动画时长
        let duration = (noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
        
        //更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - self.view.height)
        }
        
        //更新约束动画
        UIView.animateWithDuration(duration) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
        
    }
    
    
    
    // MARK: --发送点击事件
    @objc private func sendAction() {
        
        //有图片则发送有图片微博
        if pictureView.images.count > 0 {
        
            let status = textView.text!
            
            let accessToken = LLGUserAccountViewModel.sharedUserAccount.accessToken!
            
            SVProgressHUD.show()
            LLGNetworkTools.sharedTools.requestUpload(accessToken, status: status, image: pictureView.images.first!, callBack: { (response, error) -> () in
                if error != nil {
                    
                    SVProgressHUD.showErrorWithStatus("网络异常,发送失败")
                    print(error)
                    return
                }
                
                SVProgressHUD.showSuccessWithStatus("发送成功")
            })
            
            
        } else {
        
            //没有图片,则发送一条微博数据
            let status = textView.text!
            
            let accessToken = LLGUserAccountViewModel.sharedUserAccount.accessToken!
            
            SVProgressHUD.show()
            //发送微博
            LLGNetworkTools.sharedTools.update(accessToken, status: status) { (response, error) -> () in
                if error != nil {
                    
                    SVProgressHUD.showErrorWithStatus("网络异常,发送失败")
                    print(error)
                    return
                }
                
                SVProgressHUD.showSuccessWithStatus("发送成功")
            }
            
        }
    
        
    }
}


//处理toolBar点击事件
extension LLGComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    
    // MARK: --表情键盘
    func didSelectedEmoticon() {
    
        if textView.inputView == nil {
        
            //设置inputView为表情键盘
            textView.inputView = emoticonKyboard
            toolBar.swichEmoticon(true)
            
        } else {
            
            textView.inputView = nil
            toolBar.swichEmoticon(false)
        }
        
        //成为第一响应者
        textView.becomeFirstResponder()
        //刷新
        textView.reloadInputViews()

        
        
    }
    
    // MARK: --选择图片
    func didSelectedPicture() {
    
        let pictureVc = UIImagePickerController()
        
        //设置代理
        pictureVc.delegate = self
        
        //判断是否支持相机
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
            //来源类型
            pictureVc.sourceType = .Camera
        } else {
            //相册
            pictureVc.sourceType = .PhotoLibrary
        }
        
        //判断是否摄像头可用
        if UIImagePickerController.isCameraDeviceAvailable(.Front) {
            print("前置摄像头")
        } else if UIImagePickerController.isCameraDeviceAvailable(.Rear) {
            print("后置摄像头")
        } else {
            print("没有摄像头")
        }
        
        //支持编辑
//        pictureVc.allowsEditing = true
        
        presentViewController(pictureVc, animated: true, completion: nil)
    }
    
    // MARK: --UIImagePickerController代理方法
    // MARK: --选择图片
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        print(image)
        
        let scaleImage = image.scaleImageWithScaleWidth(200)

        //图片
        pictureView.addImage(scaleImage)
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: --取消
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
}

//文本视图代理方法
extension LLGComposeViewController: UITextViewDelegate {

    // MARK: --内容改变
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    // MARK: --开始滚动,取消第一响应者
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        
        self.view.endEditing(true)
    }
    
}
